import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Button, message, Pagination } from 'antd';
import { BaseMap, BookingScheduleItem, FindSchedule, FindScheduleItem, GetBookingSchedule, GetBookingScheduleRule } from '@/type/scheduleType';
import { findScheduleListAPI, getBookingScheduleRuleAPI } from '@/api/hospitalAPI/scheduleAPI';
import './Schedule.scss';
import classNames from 'classnames';

const Schedule = () => {
  const navigate = useNavigate();
  // 接收params参数
  const { hoscode, depcode } = useParams();

  // 获取可预约排班数据的数据参数
  const [page, setPage] = useState<GetBookingSchedule>({
    page: 1,
    limit: 10,
    hoscode,
    depcode,
  });
  // 当前可预约的排班数据
  const [currentCard, setCurrentCard] = useState<BookingScheduleItem>();
  // 计算出可预约排班数据
  const [bookingScheduleRule, setBookingScheduleRule] = useState<GetBookingScheduleRule>({} as GetBookingScheduleRule);
  const baseMap: BaseMap = useMemo(() => bookingScheduleRule.baseMap, [bookingScheduleRule]);
  const bookingScheduleList: BookingScheduleItem[] = useMemo(() => bookingScheduleRule.bookingScheduleList, [bookingScheduleRule]);
  const total: number = useMemo(() => bookingScheduleRule.total, [bookingScheduleRule]);

  // 获取排班数据的数据参数
  const [params, setParams] = useState<FindSchedule>({
    workData: '',
    hoscode,
    depcode,
  });
  // 排班数据
  const [scheduleList, setScheduleList] = useState<FindScheduleItem[]>([] as FindScheduleItem[]);
  // 计算的上午的号源
  const forenoonList = useMemo(() => scheduleList.filter(item => item.workTime === 0), [scheduleList]);
  // 计算的下午的号源
  const afternoonList = useMemo(() => scheduleList.filter(item => item.workTime === 1), [scheduleList]);

  /**
   * @description 获取排班数据的回调函数
   * */
  const findScheduleList = async (params: FindSchedule) => {
    try {
      const { data } = await findScheduleListAPI(params);
      setScheduleList(data);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 获取可预约排班数据的回调函数
   * */
  const getBookingScheduleRule = async (page: GetBookingSchedule) => {
    try {
      const { data } = await getBookingScheduleRuleAPI(page);
      setBookingScheduleRule(data);
      const currentCard = data.bookingScheduleList[0];
      setCurrentCard(currentCard);
      const newParams = { ...params, workData: currentCard.workDate };
      await findScheduleList(newParams);
      setParams(newParams);
    } catch (error: any) {
      message.error(error.message);
    }
  };


  /**
   *@description 页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
   *
   * */
  const changePagination = (_page: number, limit: number) => {
    const newPage = {
      ...page,
      page: _page,
      limit,
    };
    setPage(newPage);
    getBookingScheduleRule(newPage);

  };

  /**
   * @description 点击预约排班卡片的回调函数
   * */
  const changeCurrendCard = async (card: BookingScheduleItem) => {
    if (card.status === -1 || card.availableNumber === -1) return message.info('当前时间无号或者停止挂号');
    if (card.workDate === currentCard?.workDate) return;
    setCurrentCard(card);
    const newParams = { ...params, workData: card.workDate };
    await findScheduleList(newParams);
  };

  /**
   * @description 点击预约按钮的回调函数
   * */
  const handleMake = (schedule: FindScheduleItem) => {
    navigate(`/hospital/booking/${hoscode}/${schedule.id}`);
  };

  const renderStatus = (item: BookingScheduleItem) => {
    if (item.status === -1) {
      return (<span>停止挂号</span>);
    } else if (item.availableNumber === -1) {
      return (<span>无号</span>);
    } else if (item.availableNumber >= 1) {
      return (<span>有号({item.availableNumber})</span>);
    }
  };

  useEffect(() => {
    getBookingScheduleRule(page);
    window.scrollTo(0, 0);
  }, []);

  return (
    <div className="schedule">
      <div className="hos-name">
        <h2>{baseMap?.hosname} | {baseMap?.bigname}</h2>
        <div className="dep-name">{baseMap?.depname}</div>
      </div>
      <div className="card">
        <div className="date">{baseMap?.workDateString}</div>
        <div className="card-list">
          {
            bookingScheduleList?.map((item, index) => {
              return (
                <div onClick={() => changeCurrendCard(item)} className={classNames('card-item', item.workDate === currentCard?.workDate ? 'active' : '', item.status === -1 || item.availableNumber === -1 ? 'stop' : '', item.availableNumber >= 1 ? 'play' : '')} key={item.workDate}>
                  <div className="top">
                    <span>{item.workDate}</span>
                    <span>{item.dayOfWeek}</span>
                  </div>
                  <div className="bottom">
                    {
                      renderStatus(item)
                    }
                  </div>
                </div>
              );
            })
          }
        </div>
        <div className="pagination">
          <Pagination showSizeChanger onChange={changePagination} defaultCurrent={page.page} total={total} />
        </div>

        <div className="forenoon">
          <div className="header">
            <i className="iconfont icon-shangwu"></i>
            <span className="title">上午号源</span>
          </div>

          {
            forenoonList?.map(item => {
              return (
                <div className="item" key={item.id}>
                  <div className="left">
                    <div className="hos-name">{item.param.hosname} {item.title} {item.docname || '未知姓名'}</div>
                    <div className="info">主治：{item.skill}</div>
                    <div className="info">科室：{item.param.depname}</div>
                  </div>
                  <div className="right">
                    <span className="price">￥{item.amount}</span>
                    <Button type="primary" onClick={() => handleMake(item)}>预约({item.availableNumber})</Button>
                  </div>
                </div>
              );
            })
          }


        </div>

        <div className="afternoon">
          <div className="header">
            <i className="iconfont icon-xiawu"></i>
            <span className="title">下午号源</span>
          </div>
          {
            afternoonList?.map(item => {
              return (
                <div className="item" key={item.id}>
                  <div className="left">
                    <div className="hos-name"> {item.param.hosname} {item.title} {item.docname || '未知姓名'}</div>
                    <div className="info">主治：{item.skill}</div>
                    <div className="info">科室：{item.param.depname}</div>
                  </div>
                  <div className="right">
                    <span className="price">￥{item.amount}</span>
                    <Button type="primary" onClick={() => handleMake(item)}>预约({item.availableNumber})</Button>
                  </div>
                </div>
              );
            })
          }
        </div>

      </div>
    </div>
  );
};

export default Schedule;
